#include <stdio.h>
#include "key.h"
#include "systick.h"


uint8_t read_button_GPIO(uint8_t button_id)
{
	// you can share the GPIO read function with multiple Buttons
	switch(button_id)
	{
		case btn1_id:
			return GPIO_ReadInDataBit(USER_KEY_PORT,USER_KEY_PIN);
		default:
			return 0;
	}
}

#define ENABLE_KEY_INTERRUPT 1  //使用MutilButton 先注释调中断触发
//注册中断，唤醒进入WFI状态的mcu
void BOARD_UserKeyInit(void)
{
    /* 调用GPIO的HAL库对象结构体声明GPIO对象 */
    GPIO_Init_Type gpio_init;

#if ENABLE_KEY_INTERRUPT    
    
    uint32_t prioritygroup = 0;
    USER_SYSCFG_CLK_EN();
#endif
    /* 设置GPIO的模式 */
    gpio_init.PinMode  = GPIO_PinMode_In_PullUp;
    gpio_init.Speed = GPIO_Speed_50MHz;
    
    /* 选择引脚初始化 */
    gpio_init.Pins  = USER_KEY_PIN;
    GPIO_Init(USER_KEY_PORT, &gpio_init);
#if ENABLE_KEY_INTERRUPT
    /* 将外部中断线设置为复用模式 */
    SYSCFG_SetExtIntMux(SYSCFG_EXTIPort_GPIOA, SYSCFG_EXTILine_0);
    /* 设置外部中断线的触发方式 */
    EXTI_SetTriggerIn(EXTI, EXTI_LINE_0, EXTI_TriggerIn_FallingEdge); 
    /* 使能外部中断线 */
    EXTI_EnableLineInterrupt(EXTI, EXTI_LINE_0, true);
    EXTI_EnableLineEvent(EXTI, EXTI_LINE_0, true); // 唤醒mcu

    // prioritygroup = NVIC_GetPriorityGrouping();
    // NVIC_SetPriority(SysTick_IRQn, NVIC_EncodePriority(prioritygroup, 0, 0));
    /* 使能对应的外部中断 */
    NVIC_EnableIRQ(EXTI0_IRQn);
#endif
}

#if ENABLE_KEY_INTERRUPT
/* EXTI IRQ Handler */
void BOARD_EXTI_IRQHandler(void)
{
    uint32_t flags = EXTI_GetLineStatus(BOARD_EXTI_PORT);
    if ( 0u != ( flags & BOARD_EXTI_LINE ) ) /* Interrupts. */
    {
        if (0 == GPIO_ReadInDataBit(USER_KEY_PORT,USER_KEY_PIN))
        {
            printf("user key press\r\n");
        }
    }
    EXTI_ClearLineStatus(BOARD_EXTI_PORT, flags);
}
#endif